#include "../base.h"
#include <stdio.h>

#define LOG_TAG "MyView"

extern jobject getActivity();

static jclass getClass(JNIEnv* env,const char * className)
{
	return (*env)->FindClass(env,className);
}

static jclass getMyViewClass(JNIEnv* env)
{
	return getClass(env,"person/wangchen11/nativeview/MyView");
}

//创建一个自定义View
MyView newMyView()
{
	JNIEnv* env = Android_JNI_GetEnv();
	jclass clazz = getMyViewClass(env);
	static jmethodID methoID = NULL;
	if(methoID==NULL)
		methoID = (*env)->GetMethodID( env,clazz,"<init>","(Landroid/content/Context;)V" );
	jobject obj = (*env)->NewObject(env,clazz,methoID,getActivity());
	MyView view = (*env)->NewGlobalRef(env,obj);
	(*env)->DeleteLocalRef(env,obj);
	(*env)->DeleteLocalRef(env,clazz);
	return view;
}

//删除一个自定义View
void deleteMyView(MyView thiz)
{
	if(thiz==NULL)
	{
		LOGE("deleteMyView thiz==NULL");
		return ;
	}
	JNIEnv* env = Android_JNI_GetEnv();
	(*env)->DeleteGlobalRef(env,thiz);
}

//设置绘图回调
void MyView_setOnDrawListener(MyView thiz,OnDrawCallback callBack,void *data)
{
	if(thiz==NULL)
	{
		LOGE("View_setOnTouchListener thiz==NULL");
		return ;
	}
	JNIEnv* env = Android_JNI_GetEnv();
	jclass clazz = getMyViewClass(env);
	static jmethodID methoID = NULL;
	if(methoID==NULL)
		methoID = (*env)->GetMethodID(env,clazz,"setOnDrawListener","(Lperson/wangchen11/nativeview/MyView$OnDrawListener;)V");
	(*env)->DeleteLocalRef(env,clazz);
	if(callBack==NULL)
		(*env)->CallVoidMethod(env,thiz,methoID,NULL);
	else
	{
		MyListener listener = newOnDrawListener(callBack,data);
		(*env)->CallVoidMethod(env,thiz,methoID,listener);
		deleteMyListener(listener);
	}
}
